﻿using System;
using System.Net;
using shfa.snomtastic.data.business;
using shfa.snomtastic.data.security;

namespace shfa.snomtastic.web
{
    public partial class actions : System.Web.UI.Page
    {
        #region Members
        

        public string macAddress { get; set; }
        public string action { get; set; }
        public string ipAddress { get; set; }
        public string userAgent { get; set; }

        public PhoneInfo pi { get; set; }
        public AppConfig ac = new AppConfig();

        #endregion

        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            macAddress = Request.QueryString["mac"];
            action = Request.QueryString["action"];
            ipAddress = Request.UserHostAddress;
            userAgent = Request.ServerVariables["HTTP_USER_AGENT"];

            PhoneController pc = new PhoneController();
            pi = pc.SelectPhoneByMacAddress(macAddress);
            bool bUpdatePhoneInfo = false;
            if (pi != null)
            {
                switch (action)
                {
                    case "reg_failed":
                        bUpdatePhoneInfo = UpdateRegistrationFailed();
                        break;
                    case "log_on":
                        bUpdatePhoneInfo = UpdateLogin();
                        break;
                    default:
                        bUpdatePhoneInfo = false;
                        LogPhoneEvent("Action Event (" + action + ")", "Information");
                        break;
                }

                if (bUpdatePhoneInfo)
                {
                    pc.UpdatePhone(pi);
                }
            }

        }

        protected bool UpdateLogin()
        {
            if (pi != null)
            {
                LogPhoneEvent("Action: Phone Log In", "Information");
                pi.RegistrationFailed = false;
                pi.ReRegisterCount = 0;
                return true;
            }
            return false;
        }

        protected bool UpdateRegistrationFailed()
        {
          
            if (pi.UserId != Guid.Empty)
            {
                UserController uc = new UserController();
                UserInfo ui = uc.SelectUser(pi.UserId);
                if (ui != null)
                {
                    adSecurity ad = new adSecurity();

                    if (ad.accountlockedOut(ui.UserName, ui.PasswordUpdate))
                    {
                        LogPhoneEvent("Action: Registration Failed (Account Locked)", "Information");
                        pi.ReRegisterCount = 0;
                        pi.RegistrationFailed = true;
                    }
                    else
                    {
                        if (pi.ReRegisterCount == 0)
                        {
                            SendPhoneCommand(PhoneCommand.CommandType.Reregister);
                            pi.ReRegisterCount = 1;
                            pi.FirstFailedDate = DateTime.Now;
                            LogPhoneEvent("Action: Registration Failed (First)", "Information");
                        }
                        else
                        {
                            int iMaxRegAttempts;
                            int iRebootDelay;
                            try { iMaxRegAttempts = int.Parse(ac.Items["MaxRegAttempts"]); }
                            catch { iMaxRegAttempts = 5; }
                            try { iRebootDelay = int.Parse(ac.Items["RebootDelay"]); }
                            catch { iRebootDelay = 300; }
                            if (DateTime.Now < pi.FirstFailedDate.AddSeconds(iRebootDelay))
                            {
                                if (pi.ReRegisterCount == iMaxRegAttempts)
                                {
                                    SendPhoneCommand(PhoneCommand.CommandType.Reboot);
                                    pi.ReRegisterCount = 1;
                                    pi.FirstFailedDate = DateTime.Now;
                                    LogPhoneEvent("Action: Registration Failed (Phone Rebooted)","Information");
                                }
                                else
                                {
                                    SendPhoneCommand(PhoneCommand.CommandType.Reregister);
                                    pi.ReRegisterCount += 1;
                                    LogPhoneEvent("Action: Registration Failed (Try Auto Re-Register)","Information");
                                }
                            }
                            else
                            {
                                LogPhoneEvent("Action: Registration Failed (waiting for delay period)", "Information");
                                return false;
                            }
                        }
                    }
                }
                else
                {
                    LogPhoneEvent("Action: Registration Failed (User Data Error)", "Error");
                    return false;
                }

            }
            else
            {
                LogPhoneEvent("Action: Registration Failed (No User Selected)", "Error");
                return false;
            }
            return true;
        }

        #endregion

        #region Helpers

        private void LogPhoneEvent(string EventMessage, string EventType)
        {
            EventLog el = new EventLog();
            el.LogEvent(pi.PhoneId, pi.UserId, macAddress, ipAddress, userAgent, "Phone", EventMessage, EventType);
        }

        private void SendPhoneCommand(PhoneCommand.CommandType cmd)
        {
            RijndaelEnhanced re = new RijndaelEnhanced();
            PhoneCommand phCmd = new PhoneCommand(pi, cmd);
            phCmd.SendCommand();
        }

        #endregion

      


    }
}
